package org.file5.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.file5.domain.Article;
import org.file5.domain.Category;
import org.file5.domain.EntityComment;
import org.file5.domain.Person;
import org.file5.service.ServiceFascade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

@Controller
public class PersonController {
	private final Logger logger = Logger.getLogger(this.getClass());
	public static String AVATAR_DEFAULT_IMAGE = "themes/avatar_default_icon.png";
	@Autowired
	private ServiceFascade sf;
	@Autowired
	private UserService googleUserService;

	@RequestMapping(value = "/person/comment/article/{articleUid}")
	public String commentArticle(@PathVariable("articleUid") String articleUid,
			@RequestParam(value = "comment", required = false) String comment,
			@RequestParam(value = "parentCommentUid", required = false) String parentCommentUid, Model model,HttpServletRequest request) {
		if (comment != null && !comment.isEmpty() && parentCommentUid != null && !parentCommentUid.isEmpty()) {
			User googleUser = googleUserService.getCurrentUser();
			String personUid = sf.getPersonService().getPersonUid(googleUser);
			String theSiteUid = request.getServerName()
			+ (request.getServerPort() == 80 ? "" : ":" + request.getServerPort() + "");

			EntityComment ec = sf.getArticleService().addComment(articleUid, parentCommentUid, comment, personUid);
			sf.getF5XMPPService().sendArticleCommentNotification(theSiteUid, ec.getUid());



		}
		return "redirect:/article/" + articleUid + ".htm";
	}

	@RequestMapping("/person/blog/add")
	public String setPersonBlogInfo(@RequestParam(value = "blogUrl") String blogUrl,
			@RequestParam(value = "blogJid", required = false) String blogJid, Model model) {

		User googleUser = googleUserService.getCurrentUser();
		if (!googleUserService.isUserAdmin()) {
			sf.getPersonService().addUpdate(googleUser, blogUrl, blogJid);
			return "redirect:/person/home.htm";
		} else {
			return "redirect:/admin/home.htm";
		}
	}

	@RequestMapping("/person/home")
	public String home(Model model, HttpServletRequest request) {

		if (!googleUserService.isUserAdmin()) {
			User googleUser = googleUserService.getCurrentUser();
			Person person = sf.getPersonService().addUpdate(googleUser, null, null);
			model.addAttribute("person", person);
			return "person/home";
		} else {
			return "redirect:/admin/home.htm";
		}
	}

	@RequestMapping("/person/reprint/article/{articleUid}")
	public String reprintArticle(@PathVariable("articleUid") String articleUid, Model model, HttpServletRequest request) {
		User googleUser = googleUserService.getCurrentUser();
		String personUid = sf.getPersonService().getPersonUid(googleUser);
		Person person = sf.getPersonService().find(personUid);
		model.addAttribute("person", person);

		Article article = sf.getArticleService().find(articleUid, true);
		if (article.getPrimaryCategoryKey() != null) {
			List<Category> primaryCategoryTrail = sf.getCategoryService().getPrimaryCategoryTrail(
					article.getPrimaryCategoryKey());
			model.addAttribute("primaryCategoryTrail", primaryCategoryTrail);
			model.addAttribute("currentCategory", article.getPrimaryCategory());
		}
		model.addAttribute("article", article);

		return "person/articlereprintrequest";
	}

	@RequestMapping(value = "/avatar/signature/{uid}", method = RequestMethod.GET)
	public String avatarSignature(@PathVariable("uid") String uid, Model model, HttpServletRequest request) {
		Person person = sf.getBaseService().find(Person.class, uid);
		model.addAttribute("person", person);
		return "person/signature";
	}

	@RequestMapping(value = "/avatar/icon/{uid}.avatar", method = RequestMethod.GET)
	public void avatarIcon(@PathVariable("uid") String uid, HttpServletRequest req, HttpServletResponse response,
			OutputStream outputStream) throws IOException {
		Person person = sf.getBaseService().find(Person.class, uid);
		byte[] swagImageBytes;

		if (person != null && person.getAvatarIcon() != null) {
			swagImageBytes = person.getAvatarIcon().getBytes();
		} else {
			// if there's no image, return default image
			String requestURL = req.getRequestURL().toString();
			String baseURL = requestURL.substring(0, requestURL.lastIndexOf("/avatar"));
			String imgUrl = baseURL + "/" + AVATAR_DEFAULT_IMAGE;

			swagImageBytes = sf.getImageService().getImageDataFromURL(imgUrl);
		}
		try {
			outputStream.write(swagImageBytes, 0, swagImageBytes.length);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
